package com.action.wx.common;

import com.bean.*;
import com.common.BaseAction;
import com.common.ModelAndJson;
import com.common.SystemConfig;
import com.service.city.CityService;
import com.service.member.MemberService;
import com.service.merchant.MerchantService;
import com.service.order.OrderService;
import com.service.product.ProductService;
import com.service.wxconfig.WxConfigService;
import com.service.wxuser.WxUserService;
import com.util.Config;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * 通用模块
 */
@Controller
@RequestMapping("wx")
public class CommonAction extends BaseAction{
    Logger log = Logger.getLogger(CommonAction.class);
    @Autowired
    private MemberService memberService;
    @Autowired
    private WxConfigService wxConfigService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private CityService cityService;
    @Autowired
    private ProductService productService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private OrderService orderService;
    public CommonAction() {

    }
    @RequestMapping("index")
    public ModelAndView index(HttpServletRequest request, ModelMap modelMap, String code,Integer mid) {
        //orderService.sendWxMsg("oTP4fs2kPKK6vFMiyXShzjn97VbY","测试");
        HttpSession session = request.getSession();
        Member member=(Member)session.getAttribute(SystemConfig.MemberSession);
        //Wx_user wxUser=null;
        if(member==null&& StringUtils.isNotBlank(code)){
            member= wxConfigService.setMemberData(code,null);
            session.setAttribute(SystemConfig.MemberSession,member);
        }
        if(member!=null){
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            session.setAttribute(SystemConfig.openidSession,member.getOpenid());
            /*if(member.getIsactive()==0){
                if(StringUtils.isNotBlank(member.getTel())){
                    return new ModelAndView("redirect:/wx/drainage.htm", modelMap);
                }
                return new ModelAndView("redirect:/wx/welcome.htm", modelMap);
            }*/
        }
        /*调试内容开始*/
       /*mid=38;
        if(mid!=null){
            member=memberService.selectByPrimaryKey(mid);
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            session.setAttribute(SystemConfig.openidSession,member.getOpenid());
            session.setAttribute(SystemConfig.CityIdSession,2);
        }*/
        /*调试内容结束*/
        Integer curCityId = (Integer) session.getAttribute(SystemConfig.CityIdSession);
        List<City> cityList = cityService.selectList(new HashMap<String, Object>());
        if(curCityId==null){
            modelMap.put("cityList", cityList);
            return new ModelAndView("/wx/common/index", modelMap);
        }
        List<Product> recList = productService.getRecommendList(curCityId);
        modelMap.put("recList", recList);
        modelMap.put("cityList", cityList);
        modelMap.put("mid", member!=null?member.getId():null);
        return new ModelAndView("/wx/common/index", modelMap);
    }

    /**
     * 注册介绍页面 注册入口页
     * @param request
     * @param modelMap
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("welcome")
    public ModelAndView main(HttpServletRequest request, ModelMap modelMap, String code,String state) {
        HttpSession session = request.getSession();
        Integer mid=(Integer)session.getAttribute(SystemConfig.MemberIdSession);
        Member member=null;
        Wx_user wxUser=null;
        if(mid==null&& StringUtils.isNotBlank(code)){
            Integer patentId=null;
            if(StringUtils.isNotBlank(state)){
                patentId=Integer.parseInt(state);
            }
           member= wxConfigService.setMemberData(code,patentId);
           mid=member.getId();
            session.setAttribute(SystemConfig.MemberSession,member);
        }
        if(mid!=null){
            member=memberService.selectByPrimaryKey(mid);
            wxUser = wxUserService.selectByOpenId(member.getOpenid());
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            session.setAttribute(SystemConfig.openidSession,member.getOpenid());
            if(member.getCityid()!=null){
                City city = cityService.findCityById(member.getCityid());
                session.setAttribute(SystemConfig.CitySession,city);
                session.setAttribute(SystemConfig.CityIdSession,city.getId());
                session.setAttribute(SystemConfig.CityNameSession,city.getCityname());
            }
            if(member.getIsactive()!=null&&member.getIsactive()==1){
                return new ModelAndView("redirect:/wx/index.htm", modelMap);
            }
        }
        modelMap.put("wxUser",wxUser);
        modelMap.put("member", member!=null?member:null);
        modelMap.put("pid", state);
        return new ModelAndView("/wx/common/main", modelMap);
    }
    /**
     * 绑定手机号 城市页
     * @param request
     * @param modelMap
     * @param mid
     * @param cid
     * @param pid
     * @return
     */
    @RequestMapping("bind")
    public ModelAndView bind(HttpServletRequest request, ModelMap modelMap, Integer mid, Integer cid, Integer pid) {
        HttpSession session = request.getSession();
        HashMap<String, Object> paraMap = new HashMap<>();
        List<City> cityList = cityService.selectList(new HashMap<String, Object>());
        modelMap.put("cityList", cityList);
        modelMap.put("memberId", mid);
        modelMap.put("cityId", cid);
        modelMap.put("parentId", pid);
        return new ModelAndView("/wx/common/bind", modelMap);
    }

    @RequestMapping("login")
    public ModelAndView goLogin(HttpServletRequest request, ModelMap modelMap) {
        return new ModelAndView("/wx/common/login", modelMap);
    }

    /**
     * 绑定合作商
     * @param request
     * @param modelMap
     * @param mid merchantid
     * @param cid cityid
     * @return
     */
    @RequestMapping("bindmerchant")
    public ModelAndView bindMerchant(HttpServletRequest request, ModelMap modelMap,Integer mid,Integer cid ,String code) {
        modelMap.put("merchantId", mid);
        modelMap.put("cityId", cid);
        modelMap.put("code", code);
        Member member = wxConfigService.setMemberData(code, null);
        modelMap.put("member", member);
        return new ModelAndView("/wx/common/bind_merchant", modelMap);
    }

    @ResponseBody
    @RequestMapping("doBindMerchant")
    public String doBindMerchant(HttpServletRequest request,ModelAndJson modelMap, Integer mid, Integer cid,String tel,Integer memberid) {
        try {
            Member member = memberService.selectByPrimaryKey(memberid);
            if(member==null){
                modelMap.setFalse("error","会员信息异常");
                return modelMap.toString();
            }
            if(mid==null){
                modelMap.setFalse("error","绑定失败");
                return modelMap.toString();
            }
            member.setTel(tel);
            member.setCityid(cid);
            member.setIsmerchant((byte) 1);
            member.setMerchantid(mid);
            member.setIsactive((byte) 1);
            memberService.updateByPrimaryKeySelective(member);
            Merchant merchant = merchantService.findMerchantById(mid);
            merchant.setMemberid(memberid);
            merchantService.updateByPrimaryKeySelective(merchant);
            HttpSession session = this.getSession();
            City city = cityService.findCityById(cid);
            session.setAttribute(SystemConfig.CitySession,city);
            session.setAttribute(SystemConfig.CityIdSession,city.getId());
            session.setAttribute(SystemConfig.CityNameSession,city.getCityname());
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            session.setAttribute(SystemConfig.openidSession,member.getOpenid());
        }catch (Exception e){
            modelMap.setFalse("error","绑定商户出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }


    /**
     * 绑定手机号  城市动作
     * @param request
     * @param modelMap
     * @param mid
     * @param cid
     * @param pid
     * @param tel
     * @return
     */
    @ResponseBody
    @RequestMapping("doBind")
    public String doBind(HttpServletRequest request,ModelAndJson modelMap, Integer mid, Integer cid,Integer pid,String tel,String password) {
        try {
            Member member = memberService.selectByPrimaryKey(mid);
            if(member==null){
                member=new Member();
            }
            member.setTel(tel);
            member.setCityid(cid);
            if(pid!=null){
                member.setParentid(pid);
            }
            String pwd = new SimpleHash("SHA-1", tel, password).toString();	//密码加密
            member.setPassword(pwd);
            member.setLoginname(tel);
            if(member==null){
                memberService.insert(member);
            }else{
                memberService.updateByPrimaryKeySelective(member);
            }
            HttpSession session = this.getSession();
            City city = cityService.findCityById(cid);
            session.setAttribute(SystemConfig.CitySession,city);
            session.setAttribute(SystemConfig.CityIdSession,city.getId());
            session.setAttribute(SystemConfig.CityNameSession,city.getCityname());
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            session.setAttribute(SystemConfig.openidSession,member.getOpenid());
        }catch (Exception e){
            modelMap.setFalse("error","注册出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }

    @ResponseBody
    @RequestMapping("doLogin")
    public String doLogin(HttpServletRequest request,ModelAndJson modelMap,String loginName,String password) {
        try {
            Member member = memberService.getMeberByLoginName(loginName);
            if(member==null){
                modelMap.setFalse("error","手机号或密码错误");
                return modelMap.toString();
            }
            String pwd = new SimpleHash("SHA-1", loginName, password).toString();	//密码加密
            if(!member.getPassword().endsWith(pwd)){
                modelMap.setFalse("error","密码错误");
                return modelMap.toString();
            }
            HttpSession session = request.getSession();
            session.setAttribute(SystemConfig.MemberSession,member);
            session.setAttribute(SystemConfig.MemberIdSession,member.getId());
            //session.setAttribute(SystemConfig.openidSession,member.getOpenid());
        }catch (Exception e){
            modelMap.setFalse("error","登录出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }

    /**
     * 引流商品挑选页
     * @param modelMap
     * @return
     */
    @RequestMapping("drainage")
    public ModelAndView drainage(ModelMap modelMap,Integer mid) {
        HashMap<String, Object> paraMap = new HashMap<>();
        HttpSession session = this.getSession();
        Member member =(Member)session.getAttribute(SystemConfig.MemberSession);
        Integer cid = (Integer) session.getAttribute(SystemConfig.CityIdSession);
        if(mid!=null&&member==null){
            member = memberService.selectByPrimaryKey(mid);
        }
        if(member==null){
            String autoLoginUrl=Config.getString("login.index");
            modelMap.put("autoLoginUrl",autoLoginUrl);
            return new ModelAndView("/wx/common/login_error", modelMap);
        }
        if(member.getIsactive()==1){
            return new ModelAndView("redirect:/wx/index.htm", modelMap);
        }
        if(cid==null){
            cid=member.getCityid();
        }
        List proDraList=productService.getDraList(cid);
        modelMap.addAttribute("proDraList",proDraList);
        modelMap.addAttribute("mid",member.getId());
        return new ModelAndView("/wx/common/drainage", modelMap);
    }


    @ResponseBody
    @RequestMapping("setCitySession")
    public String setCitySession(HttpServletRequest request,ModelAndJson modelMap,Integer cid) {
        try {
            HttpSession session = this.getSession();
            City city = cityService.findCityById(cid);
            session.setAttribute(SystemConfig.CitySession,city);
            session.setAttribute(SystemConfig.CityIdSession,city.getId());
            session.setAttribute(SystemConfig.CityNameSession,city.getCityname());
        }catch (Exception e){
            modelMap.setFalse("error","短信发送出现异常");
            return modelMap.toString();
        }
        return modelMap.toString();
    }


    /**
     * 微信用户登录失效跳转的页面
     * @param modelMap
     * @return
     */
    @RequestMapping("loginError")
    public ModelAndView loginError(ModelMap modelMap) {
        String autoLoginUrl=Config.getString("login.index");
        modelMap.put("autoLoginUrl",autoLoginUrl);
        return new ModelAndView("/wx/common/login_error", modelMap);
    }
}
